from .forms import FoodForm, CategoryForm, StorageLocationForm
from django.shortcuts import render, get_object_or_404
from .models import Food, FoodCategory, ScanRecord, StorageLocation  
from django.db.models import Count, Q
from datetime import date
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.shortcuts import render, redirect  # 添加redirect导入
from django.contrib.auth.decorators import login_required
from datetime import date,timedelta
from django.db.models import ExpressionWrapper, F, fields
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from .models import StorageLocation, Food
import json


def get_child_locations(request, parent_id):
    locations = StorageLocation.objects.filter(parent_id=parent_id)
    data = [{"id": loc.id, "name": loc.name} for loc in locations]
    return JsonResponse(data, safe=False)

# @login_required
# @user_passes_test(lambda u: u.is_superuser)
# def admin_dashboard(request):
#     foods = Food.objects.all()
#     categories = FoodCategory.objects.all()
#     scan_records = ScanRecord.objects.all()
#     return render(request, 'admin/dashboard.html', {
#         'foods': foods,
#         'categories': categories,
#         'scan_records': scan_records,
#     })
@login_required
def home(request):
    today = date.today()
    
    stats = {
        'expired_count': Food.objects.filter(expiration_date__lt=today).count(),
        'expiring_soon_count': Food.objects.filter(
            expiration_date__gte=today,
            expiration_date__lte=today + timedelta(days=7)
        ).count()
    }
    return render(request, 'home.html', {'stats': stats})  # 删除嵌套的location_qr_code定义

# 将location_qr_code移动到视图函数外部
@login_required
def location_qr_code(request, location_id):
    """处理位置二维码查看请求"""
    location = get_object_or_404(StorageLocation, id=location_id)
    children = StorageLocation.objects.filter(parent=location)
    foods = Food.objects.filter(location=location)
    return render(request, 'food_management/location_qr_view.html', {
        'location': location,
        'children': children,
        'foods': foods
    })
@login_required
def add_food(request):
    # 获取完整的层级位置数据
    locations = StorageLocation.objects.filter(user=request.user).select_related('parent')
    
    if request.method == 'POST':
        form = FoodForm(request.POST)
        form.fields['location'].queryset = StorageLocation.objects.filter(user=request.user)
        if form.is_valid():
            food = form.save(commit=False)
            food.user = request.user
            food.save()
            return render(request, 'food_management/success.html', {'food': food})
    else:
        form = FoodForm(initial={'user': request.user})
    
     # 构建位置树结构
    location_tree = {}
    for loc in locations:
        if loc.level == 1:
            location_tree[loc.id] = {
                'name': loc.name,
                'children': {}
            }
        elif loc.level == 2 and loc.parent:
            if loc.parent.id in location_tree:
                location_tree[loc.parent.id]['children'][loc.id] = {
                    'name': loc.name,
                    'children': {}
                }
        elif loc.level == 3 and loc.parent and loc.parent.parent:
            if loc.parent.parent.id in location_tree and loc.parent.id in location_tree[loc.parent.parent.id]['children']:
                location_tree[loc.parent.parent.id]['children'][loc.parent.id]['children'][loc.id] = {
                    'name': loc.name
                }

    return render(request, 'food_management/add_food.html', {
        'form': form,
        'location_tree_json': json.dumps(location_tree),
        'has_level1': bool(location_tree)  # 添加这个上下文变量
    })

def scan_query(request):
    if request.method == 'POST':
        # 修复获取方式，添加空值校验
        food_id = request.POST.get('food_id')
        if not food_id:
            return render(request, 'food_management/scan_query.html', {
                'error': '请输入有效的食品ID'
            })
        try:
            food = Food.objects.get(id=int(food_id))
            return redirect('scan_record', food_id=food.id)
        except (ValueError, Food.DoesNotExist):
            return render(request, 'food_management/scan_query.html', {
                'error': '未找到该食品，请检查ID是否正确'
            })
    return render(request, 'food_management/scan_query.html')
@login_required
def manage_locations(request):
    # 确保默认厨房存在
    default_kitchen, created = StorageLocation.objects.get_or_create(
        name='厨房',
        level=1,
        user=request.user,
        defaults={'parent': None}
    )
    if not default_kitchen.qr_code:  # 新增二维码检查
        default_kitchen.generate_qr_code()
    # 初始化表单（新增部分）
    if request.method == 'POST':
        form = StorageLocationForm(request.POST)
        if form.is_valid():
            new_loc = form.save(commit=False)
            new_loc.user = request.user
            # 处理层级逻辑
            if new_loc.parent:
                new_loc.level = new_loc.parent.level + 1
            else:
                new_loc.level = 1
            new_loc.save()
            return redirect('manage_locations')
    else:
        # 初始化空表单并设置父级选项
        form = StorageLocationForm()
        form.fields['parent'].queryset = StorageLocation.objects.filter(user=request.user)
    # 获取用户所有位置（包含默认厨房）
    all_locations = StorageLocation.objects.filter(user=request.user).select_related('parent')
    
    # 构建树形结构
    location_tree = []
    node_map = {}
    
    # 创建所有节点的引用
    for loc in all_locations:
        node_map[loc.id] = {
            'id': loc.id,
            'name': loc.name,
            'level': loc.level,
            'children': [],
            'get_level_display': loc.get_level_display()
        }
    
    # 构建层级关系
    for loc in all_locations:
        node = node_map[loc.id]
        if loc.parent:
            parent_node = node_map.get(loc.parent.id)
            if parent_node:
                parent_node['children'].append(node)
        else:
            location_tree.append(node)
    return render(request, 'food_management/manage_locations.html', {
        'form': form,
        'location_tree': location_tree,
        'default_kitchen': default_kitchen  # 添加上下文变量
    })
@login_required
def edit_location(request, location_id):
    location = get_object_or_404(StorageLocation, id=location_id, user=request.user)
    
    if request.method == 'POST':
        form = StorageLocationForm(request.POST, instance=location)
        if form.is_valid():
            edited_loc = form.save(commit=False)
            parent = form.cleaned_data.get('parent')
            # 处理父级关联逻辑
            if parent:
                edited_loc.level = parent.level + 1
            else:
                edited_loc.level = 1
            edited_loc.save()
            return redirect('manage_locations')
    else:
        form = StorageLocationForm(instance=location)
        form.fields['parent'].queryset = StorageLocation.objects.filter(
            user=request.user
        ).exclude(id=location_id)
    
    return render(request, 'food_management/edit_location.html', {'form': form})

@login_required
def delete_location(request, location_id):
    location = get_object_or_404(StorageLocation, id=location_id, user=request.user)

    # 级联删除辅助函数
    def delete_children(loc):
        for child in loc.storagelocation_set.all():
            delete_children(child)
            child.delete()
    
    if request.method == 'POST':
        try:
            # 禁止删除默认厨房
            if location.name == '厨房' and location.level == 1:
                return JsonResponse({'status': 'error', 'message': '默认厨房不可删除'}, status=400)
                
            delete_children(location)
            location.delete()
            return JsonResponse({'status': 'success'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    
    return JsonResponse({'status': 'error', 'message': '无效请求方法'}, status=400)
def all_foods(request):
    today = date.today()
    # 移除错误的annotate计算
    foods = Food.objects.all()
    
    # 添加位置筛选（增加有效性验证）
    selected_location = request.GET.get('location')
    
    if selected_location and selected_location.isdigit():
        foods = foods.filter(location_id=int(selected_location))

    # 重构位置树构建逻辑
    location_tree = {}
    if request.user.is_authenticated:
        locations = StorageLocation.objects.filter(user=request.user).select_related('parent')
        # 先构建所有节点
        nodes = {loc.id: {'id': loc.id, 'name': loc.name, 'children': {}} for loc in locations}
        # 建立层级关系
        for loc in locations:
            if loc.parent:
                if loc.parent.id in nodes:
                    nodes[loc.parent.id]['children'][loc.id] = nodes[loc.id]
            else:
                location_tree[loc.id] = nodes[loc.id]
    
    return render(request, 'food_management/all_foods.html', {
        'foods': foods,
        'location_tree': location_tree,
        'location_tree_json': json.dumps(location_tree),
        'selected_location': selected_location,
        'title': '所有食品列表'
    })
def manage_categories(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('manage_categories')
    else:
        form = CategoryForm()
    
    categories = FoodCategory.objects.all()
    return render(request, 'food_management/manage_categories.html', {
        'form': form,
        'categories': categories
    })
# 修改edit_category视图的模板路径
@login_required
def edit_category(request, category_id):
    category = get_object_or_404(FoodCategory, id=category_id)
    
    if request.method == 'POST':
        form = CategoryForm(request.POST, instance=category)
        if form.is_valid():
            form.save()
            return redirect('manage_categories')
        # 保留表单错误上下文 ↓
        return render(request, 'food_management/edit_category.html', {'form': form})
        
    form = CategoryForm(instance=category)
    return render(request, 'food_management/edit_category.html', {'form': form})
@login_required
def delete_category(request, category_id):
    category = get_object_or_404(FoodCategory, id=category_id)
    if request.method == 'POST':
        category.delete()
        return JsonResponse({'status': 'success'})
    return JsonResponse({'status': 'error', 'message': '无效请求'})

# def statistics(request):
#     today = date.today()
    
#     # 统计各状态食品数量
#     stats = {
#         'expired': Food.objects.filter(expiration_date__lt=today).count(),
#         'expiring_soon': Food.objects.filter(
#             expiration_date__gte=today,
#             expiration_date__lte=today + timedelta(days=7)
#         ).count(),
#         'safe': Food.objects.filter(expiration_date__gt=today + timedelta(days=7)).count()
#     }
    
#     # 分类统计
#     category_stats = FoodCategory.objects.annotate(
#         total=Count('food'),
#         expired=Count('food', filter=Q(food__expiration_date__lt=today))
#     )
    
#     return render(request, 'food_management/statistics.html', {
#         'stats': stats,
#         'category_stats': category_stats
#     })
def edit_food(request, food_id):
    food = get_object_or_404(Food, id=food_id, user=request.user)
    if request.method == 'POST':
        form = FoodForm(
            request.POST, 
            request.FILES,
            instance=food,
            # 新增初始化数据
            initial={
                'category': food.category,
                'location': food.location
            }
        )
        if form.is_valid():
            # 确保关联字段正确
            saved_food = form.save(commit=False)
            saved_food.user = request.user
            saved_food.category = form.cleaned_data.get('category', food.category)
            saved_food.location = form.cleaned_data.get('location', food.location)
            saved_food.save()
            return redirect('scan_record', food_id=saved_food.id)
        # 保留表单错误 ↓
        print("表单错误详情:", form.errors.as_json())
        return render(request, 'food_management/edit_food.html', {'form': form, 'food': food})
    else:
        form = FoodForm(instance=food)
    
    return render(request, 'food_management/edit_food.html', {
        'form': form,
        'food': food
    })
def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('/')
    else:
        form = UserCreationForm()
    return render(request, 'registration/register.html', {'form': form})

def scan_record(request, food_id):
    # 在原有代码前添加二维码内容验证
    try:
        food = Food.objects.get(id=int(food_id))
    except (ValueError, Food.DoesNotExist):
        return render(request, 'food_management/scan_query.html', {
            'error': '未找到该食品，请检查二维码是否正确'
        })
    return render(request, 'food_management/scan_result.html', {'food': food})


def expired_foods(request):
    today = date.today()
    foods = Food.objects.filter(expiration_date__lt=today)
    return render(request, 'food_list.html', {
        'foods': foods,
        'title': '已过期食品列表'
    })

def expiring_foods(request):
    today = date.today()
    foods = Food.objects.filter(
        expiration_date__gte=today,
        expiration_date__lte=today + timedelta(days=7)
    )
    return render(request, 'food_list.html', {
        'foods': foods,
        'title': '即将过期食品列表'
    })
@login_required
def delete_food(request, food_id):
    food = get_object_or_404(Food, id=food_id, user=request.user)
    if request.method == 'POST':
        food.delete()
        return redirect(request.META.get('HTTP_REFERER', '/'))
    return redirect('home')
def print_qr_codes(request):
    if request.method == 'POST':
        food_ids = request.POST.getlist('food_ids')
        foods = Food.objects.filter(id__in=food_ids)
        return render(request, 'food_management/print_qr_codes.html', {'foods': foods})
    return redirect('all_foods')
def statistics(request):
    today = date.today()

    # 过期状态统计
    expired_count = Food.objects.filter(expiration_date__lt=today).count()
    expiring_soon_count = Food.objects.filter(
        expiration_date__gte=today,
        expiration_date__lte=today + timedelta(days=7)
    ).count()
    safe_count = Food.objects.filter(expiration_date__gt=today + timedelta(days=7)).count()

    # 分类统计
    category_stats = FoodCategory.objects.annotate(
        total=Count('food'),
        expired=Count('food', filter=Q(food__expiration_date__lt=today)),
        expiring_soon=Count('food', filter=Q(
            food__expiration_date__gte=today,
            food__expiration_date__lte=today + timedelta(days=7)
        )),
        safe=Count('food', filter=Q(food__expiration_date__gt=today + timedelta(days=7)))
    )

    context = {
        'expired_count': expired_count,
        'expiring_soon_count': expiring_soon_count,
        'safe_count': safe_count,
        'category_stats': category_stats,
    }
    return render(request, 'food_management/statistics.html', context)